﻿<!DOCTYPE html>
<html>
<head>
    <title>虹口社区教育教学评比</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta content="yes" name="apple-mobile-web-app-capable" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <link rel="stylesheet" type="text/css" href="../asset/css/reset.css" />
    <link rel="stylesheet" type="text/css" href="../asset/css/photo.css" />
    <link rel="stylesheet" type="text/css" href="../asset/css/dialog.css" />
    <link rel="stylesheet" type="text/css" href="../asset/css/animate.min.css" />
    <script type="text/javascript">
        function GetQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }

        function getCookie(c_name) {
            if (document.cookie.length > 0) {
                c_start = document.cookie.indexOf(c_name + "=")
                if (c_start != -1) {
                    c_start = c_start + c_name.length + 1
                    c_end = document.cookie.indexOf(";", c_start)
                    if (c_end == -1) c_end = document.cookie.length
                    return unescape(document.cookie.substring(c_start, c_end))
                }
            }
            return ""
        }

        //为在浏览器中调试故注销下面几行与微信客户端相关代码

        //var _code = GetQueryString("code")

        //if (_code === null) {
        //    window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb1f3698b4c90dccd&redirect_uri=http://www.shtraining.net/wxdemo/photos/index.html&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
        //}
    </script>
</head>
<body>
    <section class="wrapper">
        <div id="main_photoindex" class="main"></div>
        <div id="main_photos" class="main hidden">
            <ul class="tab_title">
                <li id="lastest" class="lastestactive"></li>
                <li id="hot" class="hot"></li>
            </ul>
            <div class="tab_content" style="padding-bottom: 60px;">
                <div id="list_lastest"></div>
                <div id="list_tops" class="hidden"></div>
            </div>
        </div>
        <div id="main_upload" class="main hidden"></div>
        <div id="main_search" class="main hidden"></div>
        <div id="main_my" class="main hidden"></div>
    </section>
    <div id="nav_main">
        <div class="left"><span href="index.html" class="nav_item" id="a_photoindex"></span></div>
        <div class="left"><span class="nav_item" id="a_photos"></span></div>
        <div class="left middle_nav_item"><span class="nav_item middle" id="a_upload"></span></div>
        <div class="right"><span class="nav_item" id="a_my"></span></div>
        <div class="right"><span class="nav_item" id="a_search"></span></div>
    </div>

    <script id="list" type="text/html">
        <div class="waterfall">
            {{each photos item index}}
            <div class="item">
                <div class="item-content">
                    <span class="item-cover" data_Id="{{item.ID}}" style="background-image: url('../uploads/images/{{item.ImageUrl}}');"></span>
                </div>
                <div class="item-bar">
                    <span class="thumbup_total" data_photoId="{{item.ID}}" data_total="{{item.LikesCount}}" data_type="list">{{item.LikesCount}} 票</span>
                    <span class="thumbup_btn" data_photoId="{{item.ID}}" data_isLiked="{{item.IsLiked}}" {{if item.IsLiked =="1"}} style="background-color:#cccccc;" {{/if}}>&nbsp;&nbsp;&nbsp;&nbsp;赞</span>
                </div>
            </div>
            {{/each}}
        </div>
        <div class="center">
            <span class="more">点击显示更多</span>
            <span class="no_more hidden">已显示全部照片</span>
        </div>
    </script>
    <script id="listMore" type="text/html">
        {{each photos item index}}
        <div class="item">
            <div class="item-content">
                <span class="item-cover" data_Id="{{item.ID}}" style="background-image: url('../uploads/images/{{item.ImageUrl}}');"></span>
            </div>
            <div class="item-bar">
                <span class="thumbup_total" data_photoId="{{item.ID}}" data_total="{{item.LikesCount}}" data_type="list">{{item.LikesCount}} 票</span>
                <span class="thumbup_btn" data_photoId="{{item.ID}}" data_isLiked="{{item.IsLiked}}" {{if item.IsLiked =="1"}} style="background-color:#cccccc;" {{/if}}>&nbsp;&nbsp;&nbsp;&nbsp;赞</span>
            </div>
        </div>
        {{/each}}
    </script>
    <script type="text/html" id="photoViewer">
        <h1 class="form_title">{{pageTitle}}</h1>
        <div class="form_area">
            {{if status == "viewer"}}
            <div id="photoCover" style="background-image: url('../uploads/images/{{ImageUrl}}');"></div>
            {{else}}
            <div><p style="font-size: 14px; color: #cccccc; line-height: 2;">上传照片（每次上传 1 张照片，每人每天可上传5张）</p></div>
            <div id="photoCover">+</div>
            {{/if}}
        </div>
        <div class="form_line">
            <textarea id="txtComment" placeholder="在此可以为您的照片添加描述" class="form_input input_text f-14">{{Title}}</textarea>
        </div>
        <div class="form_line">
            <p class="tip-error">* 照片描述请不要超过50个字</p>
        </div>
        <div class="form_line">
            {{if status == "viewer"}}
            <button class="button primary-button" id="btnSavePhoto">保存</button>
            <button class="button" id="btnDelPhoto">删除</button>
            <button class="button" id="btnBack">返回</button>
            {{else if status == "upload"}}
            <button class="button primary-button" id="btnAddPhoto">确认提交</button>
            {{else}}
            <!--<button class="button primary-button" id="btnAddPhoto" disabled="disabled">确认提交</button>-->
            {{/if}}
        </div>
    </script>
    <script type="text/html" id="search">
        <div class="form_line">
            <input type="text" id="txtSearch" placeholder="请输入照片编号或作者姓名" class="form_input input_text" />
        </div>
        <div class="form_line">
            <button class="button primary-button" id="btnSearch">搜索</button>
        </div>
        <div id="searchResultList"></div>
    </script>
    <script type="text/html" id="reg">
        <h1 class="form_title">{{title}}</h1>
        <div class="form_line">
            <input type="text" id="txtUserName" placeholder="请输入您的姓名" class="form_input input_text" />
        </div>
        <div class="form_line">
            <input type="text" id="txtMobile" placeholder="请输入您的手机号" class="form_input input_text" />
        </div>
        <div class="form_line {{hideInLogin}}">
            <select id="txtSchool" class="form_input input_select">
                <option disabled selected class="hidden">请选择您的学校</option>
                <option value="第一中心小学">第一中心小学</option>
                <option value="永清路小学">永清路小学</option>
                <option value="水产路小学">水产路小学</option>
                <option value="同泰路小学">同泰路小学</option>
                <option value="和衷小学">和衷小学</option>
                <option value="淞一小学">淞一小学</option>
                <option value="淞滨路小学">淞滨路小学</option>
                <option value="泗东小学">泗东小学</option>
            </select>
        </div>
        <div class="form_line {{hideInLogin}}">
            <select id="txtRole" class="form_input input_select">
                <option disabled="disabled" selected="selected" class="hidden">请选择您的身份</option>
                <option value="1">教师</option>
                <option value="2">学生</option>
                <option value="3">家长</option>
            </select>
        </div>
        <div class="form_line">
            <p class="tip-error hidden">* 请输入正确的姓名、手机号、学校和身份</p>
        </div>
        <div class="form_line">
            <button class="button primary-button {{hideInReg}}" id="btnLogin">登录</button>
            <button class="button primary-button {{hideInLogin}}" id="btnReg">注册</button>
            <button class="button {{hideInReg}}" id="btnGoReg">我要注册</button>
            <button class="button {{hideInLogin}}" id="btnGoLogin">我要登录</button>
        </div>
    </script>
    <script type="text/html" id="myPhotos">
        <h1 class="form_title">{{title}}</h1>
        <div class="form_area">
            <div>
                <h2 class="text_area_title">我的照片</h2>
                <ul id="myPhotosList">
                    {{each photos item index}}
                    {{if item.ImageUrl != ""}}
                    <li data_id="{{item.ID}}" style="background-image: url('../uploads/images/{{item.ImageUrl}}');"></li>
                    {{else}}
                    <li class="empty"></li>
                    {{/if}}
                    {{/each}}
                </ul>
            </div>
        </div>
        <div class="form_line">
            <button class="button primary-button" id="btnGoProfile">修改个人信息</button>
            <button class="button" id="btnLogOff">退出登录</button>
        </div>
    </script>
    <script type="text/html" id="profile">
        <h1 class="form_title">{{pageTitle}}</h1>
        <div class="form_line">
            <input type="text" id="txtUserName" placeholder="请输入您的姓名" class="form_input input_text" value="{{user.UserName}}" />
        </div>
        <div class="form_line">
            <input type="text" id="txtMobile" placeholder="请输入您的手机号" class="form_input input_text" value="{{user.Mobile}}" />
        </div>
        <div class="form_line">
            <select id="txtSchool" class="form_input input_select">
                <option value="第一中心小学" {{if user.Orginazation === "第一中心小学"}} selected="selected" {{/if}}>第一中心小学</option>
                <option value="永清路小学" {{if user.Orginazation === "永清路小学"}} selected="selected" {{/if}}>永清路小学</option>
                <option value="水产路小学" {{if user.Orginazation === "水产路小学"}} selected="selected" {{/if}}>水产路小学</option>
                <option value="同泰路小学" {{if user.Orginazation === "同泰路小学"}} selected="selected" {{/if}}>同泰路小学</option>
                <option value="和衷小学" {{if user.Orginazation === "和衷小学"}} selected="selected" {{/if}}>和衷小学</option>
                <option value="淞一小学" {{if user.Orginazation === "淞一小学"}} selected="selected" {{/if}}>淞一小学</option>
                <option value="淞滨路小学" {{if user.Orginazation === "淞滨路小学"}} selected="selected" {{/if}}>淞滨路小学</option>
                <option value="泗东小学" {{if user.Orginazation === "泗东小学"}} selected="selected" {{/if}}>泗东小学</option>
            </select>
        </div>
        <div class="form_line">
            <select id="txtRole" class="form_input input_select">
                <option value="1" {{if user.RoleID === 1}} selected="selected" {{/if}}>教师</option>
                <option value="2" {{if user.RoleID === 2}} selected="selected" {{/if}}>学生</option>
                <option value="3" {{if user.RoleID === 3}} selected="selected" {{/if}}>家长</option>
            </select>
        </div>
        <div class="form_line">
            <p class="tip-error hidden">* 请输入正确的姓名、手机号、学校和身份</p>
        </div>
        <div class="form_line">
            <button class="button primary-button" id="btnSaveUser">保存</button>
            <button class="button" id="btnBack">返回</button>
        </div>
    </script>
    <script type="text/html" id="tplModal">
        <div id="modalContainer"></div>
        <div id="photoCard" class="modal">
            <span class="close" style="background-image: url('../asset/images/icon/close.png');"></span>
            <div class="card animated zoomIn fast" style="animation-duration: 300ms;">
                <img class="photo {{if Title == ""}}no_title{{/if}}" src="../uploads/images/{{ImageUrl}}" />
                <div class="number"><span>&nbsp;&nbsp;No.{{Number}}</span><span>{{UserName}}</span><span data_type="modal">{{LikesCount}} 票&nbsp;&nbsp;</span></div>
                {{if Title != ""}}
                <div class="comment"><p>{{Title}}</p></div>
                {{/if}}
                <div class="bar"><span class="btn" data_photoId="{{ID}}" data_isLiked="{{IsLiked}}" {{if IsLiked =="1"}} style="background-color:#cccccc;" {{/if}}>给他点赞</span></div>
            </div>
        </div>
    </script>

    <script src="../asset/js/template-web.js"></script>
    <script src="../asset/js/zepto.min.js" type="text/javascript"></script>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js" type="text/javascript"></script>
    <script src="../asset/js/axios.min.js"></script>
    <script src="../asset/js/selector.js" type="text/javascript"></script>
    <script src="../asset/js/utils.js?v=030801" type="text/javascript"></script>
    <script src="../asset/js/dialog.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var user = {};
        var toast;
        var toastLoading;
        var openId = "";
        var tmpUploadImageUrl = "";

        $(document).ready(function () {

            initPage();

            $(".tab_title li").click(function () {
                if ($(this).attr("id") == "lastest") {

                    $("#lastest").attr("class", "lastestactive");
                    $("#hot").attr("class", "hot");
                }

                if ($(this).attr("id") == "hot") {
                    $("#lastest").attr("class", "lastest");
                    $("#hot").attr("class", "hotactive");
                }

                var index = $(".tab_title li").index(this);
                //$(".waterfall").hide();
                //$(".waterfall:eq(" + index + ")").show();

                $(".tab_content>div").hide();
                $(".tab_content>div:eq(" + index + ")").show();

                if (index == 0) {
                    getLastestPhotos();
                }

                if (index == 1) {
                    getTopsPhotos();
                }
            });

        });

        function bindMenuClick() {
            $(".nav_item").click(function () {
                var menuToPage = $(this).attr("id").split("_")[1]
                setNavStatus(menuToPage);
                setContentStatus(menuToPage);
            });
        }

        function setNavStatus(id) {
            $("#a_photoindex").css("background-image", "url('../asset/images/btn_photoindex.png')");
            $("#a_photos").css("background-image", "url('../asset/images/btn_photos.png')");
            $("#a_upload").css("background-image", "url('../asset/images/btn_upload.png')");
            $("#a_search").css("background-image", "url('../asset/images/btn_search.png')");
            $("#a_my").css("background-image", "url('../asset/images/btn_my.png')");

            $("#a_" + id).css("background-image", "url('../asset/images/btn_" + id + "_focus.png')");
        }

        function setContentStatus(id) {
            $(".main").hide();
            $("#main_" + id).addClass("animated slideInUp faster").show();

            if (id === "photos") {
                initPhotosPage();
            }

            if (id === "upload") {
                if (user === "") {
                    setNavStatus("my");
                    $(".main").hide();
                    $("#main_my").show();

                    initLoginPage();
                } else {
                    initUploadPage();
                }
            }

            if (id === "search") {
                initSearchPage();
            }

            if (id === "my") {
                if (user === "") {
                    initLoginPage();
                } else {
                    initMyPhotosPage();
                }
            }

        }

        function initPhotosPage() {

            showLoading("数据加载中");

            getLastestPhotos();
        }

        function getWeiXinJS() {
            var _baseUrl = "http://www.shtraining.net/wxdemo/photos/index.html";
            var _querystring = "code=" + _code + "&state=1";
            console.log(_baseUrl + "?" + _querystring);
            $.ajax({
                url: "../api/accesstoken/getjssdkconfig?baseurl=" + _baseUrl + "&querystring=" + _querystring,
                dataType: "json",
                type: "GET",
                error: function (xhr, status, error) {
                    console.log(error)
                },
                success: function (result) {
                    //console.log(result);
                    var config = result;
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: config.appid, // 必填，公众号的唯一标识
                        timestamp: config.timestamp, // 必填，生成签名的时间戳
                        nonceStr: config.nonceStr, // 必填，生成签名的随机串
                        signature: config.signature,// 必填，签名
                        jsApiList: ['chooseImage', 'uploadImage'] // 必填，需要使用的JS接口列表
                    });
                }
            });
        }

        function openWeiXinAlbum() {

            wx.chooseImage({
                count: 1, // 默认9
                sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                    console.log(localIds);
                    uploadPhotoToWeiXin(localIds[0]);
                }
            });
        }

        //上传图片到微信服务器
        function uploadPhotoToWeiXin(localId) {
            wx.uploadImage({
                localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得
                isShowProgressTips: 1, // 默认为1，显示进度提示
                success: function (res) {
                    var serverId = res.serverId; // 返回图片的服务器端ID

                    console.log(serverId);
                    //$("#spServerID").html(serverId);

                    $.ajax({
                        url: "../api/accesstoken/downloadimage?media_id=" + serverId,
                        dataType: "text",
                        type: "GET",
                        error: function (data) {
                            console.log(data);
                        },
                        success: function (result) {
                            console.log(result);
                            var imgUrl = "../uploads/images/" + eval("(" + result + ")");
                            tmpUploadImageUrl = eval("(" + result + ")");
                            $("#photoCover").css("background-image", "url(\'" + imgUrl + "\')").empty();
                        }
                    });
                }
            });
        }

        function initUploadPage() {

            checkUploadImageCount(function (count) {

                var data = {};
                data.pageTitle = "上传照片";
                data.status = count > 4 ? "disabled" : "upload";
                data.imgUrl = "";
                data.comment = "";

                console.log(data);

                //var data = JSON.parse("{\"pageTitle\":\"上传照片\", \"status\":\"upload\", \"imgUrl\":\"\", \"comment\":\"\"}");
                var html = template("photoViewer", data);
                $("#main_upload").html(html);

                getWeiXinJS();

                $("#photoCover").click(function () {
                    openWeiXinAlbum();
                });

                $("#btnAddPhoto").click(function () {
                    var _comment = $("#txtComment").val();

                    console.log(_comment);

                    if (_comment.length > 50) {
                        showError("照片描述超过50个字");
                    } else {
                        addPhoto(tmpUploadImageUrl, _comment);
                    }

                });


            });


        }

        function checkUploadImageCount(callback) {
            var getTodayUploadImageCountUrl = "../api/photoitem?where= and  wechatopenid='" + openId + "' and createdat between '" + getToday() + "' and '" + getTomorrow() + "'";

            //获取当前用户当天上传的图片
            $.getJSON(getTodayUploadImageCountUrl, function (res) {
                callback(res.count)
            });
        }

        function initSearchPage() {
            var data = {};
            var html = template("search", data);
            $("#main_search").html(html);

            $("#btnSearch").click(function () {
                var reg = /^[0-9]+.?[0-9]*$/;
                var searchUrl;
                if (reg.test($("#txtSearch").val())) {
                    searchUrl = "../api/photoitem?where=and Number=" + $("#txtSearch").val();
                } else {
                    searchUrl = "../api/photoitem?where=and UserName = \'" + $("#txtSearch").val() + "\'";
                }
                $.getJSON(searchUrl, function (res) {
                    if (res.count > 0) {
                        var data = {};
                        data.photos = [];
                        data.photos = res.results;

                        var html = template("list", data);
                        $("#searchResultList").html(html);
                        bindLikeClick();
                        bindPhotoClick();
                        $(".more").hide();
                    } else {
                        $("#searchResultList").html("<p class=\"center f-14\">未搜索到符合条件的照片</p>");
                    }
                });
            });
        }

        function initLoginPage() {
            var data = JSON.parse("{\"title\":\"登录\", \"hideInReg\":\"\", \"hideInLogin\":\"hidden\"}");
            var html = template("reg", data);
            $("#main_my").html(html);

            $("#btnLogin").click(function () {
                var _userName = $("#txtUserName").val();
                var _mobile = $("#txtMobile").val();

                if (_userName === "" || _mobile === "" || _mobile.length !== 11) {
                    $(".tip-error").show();
                    return;
                } else {
                    $(".tip-error").hide();
                }

                login(_userName, _mobile);
            });

            $("#btnGoReg").click(function () {
                initRegPage();
            });
        }

        function initRegPage() {
            var data = JSON.parse("{\"title\":\"注册\", \"hideInReg\":\"hidden\", \"hideInLogin\":\"\"}");
            var html = template("reg", data);
            $("#main_my").html(html);

            $("#btnReg").click(function () {
                var _username = $("#txtUserName").val();
                var _mobile = $("#txtMobile").val();
                var _school = $("#txtSchool").val();
                var _role = $("#txtRole").val();

                if (_username === "" || _mobile === "" || _school === "" || _role === "" || _mobile.length !== 11) {
                    $(".tip-error").show();
                    return;
                } else {
                    $(".tip-error").hide();
                }

                reg(_username, _mobile, _school, _role);
            });

            $("#btnGoLogin").click(function () {
                initLoginPage();
            });
        }

        function initProfilePage() {
            var data = {};
            data.pageTitle = "个人信息";
            data.user = user;
            var html = template("profile", data);
            $("#main_my").html(html);

            $("#btnSaveUser").click(function () {
                var model = user;
                model.ID = user.ID;
                model.UserName = $("#txtUserName").val();
                model.Mobile = $("#txtMobile").val();
                model.Orginazation = $("#txtSchool").val();
                model.RoleID = $("#txtRole").val();
                saveUser(model);
            });

            $("#btnBack").click(function () {
                initMyPhotosPage();
            });
        }

        function initMyPhotosPage() {
            var data = JSON.parse("{\"title\":\"我的\", \"photos\":[]}");

            showLoading("数据加载中");

            $.getJSON("../api/photoitem?where=and userid=\'" + user.ID + "\'", function (res) {

                if (res.count !== 0) {
                    data.photos = res.results;
                }

                for (var i = 0; i < ((Math.floor(res.count / 4) + 1) * 4 - res.count); i++) {
                    data.photos.push({ "ImageUrl": "" });
                }

                var html = template("myPhotos", data);
                $("#main_my").html(html);

                toastLoading.close();

                $("#btnGoProfile").click(function () {
                    initProfilePage();
                });

                $("#btnLogOff").click(function () {
                    delCookie("wusong_photo_user");
                    user = "";
                    initLoginPage();
                });

                $("#myPhotosList li:not(.empty)").click(function () {
                    var imageId = $(this).attr("data_id");
                    initPhotoViewer(imageId);
                });

                toastLoading.close();
            })
        }

        function initPhotoViewer(id) {
            var getItemUrl = "../api/photoitem/" + id;

            $.getJSON(getItemUrl, function (res) {
                //var data = JSON.parse("{\"title\":\"照片信息\", \"status\":\"viewer\", \"imgUrl\":\"../asset/images/1.jpg\", \"comment\":\"我爱我的祖国\"}");
                var data = res.result;
                data.status = "viewer";
                data.pageTitle = "照片信息";

                var html = template("photoViewer", data);
                $("#main_my").html(html);

                $("#btnSavePhoto").click(function () {
                    var _comment = $("#txtComment").val();
                    if (_comment.length <= 50) {
                        var _photo = {};
                        _photo.ID = data.ID;
                        _photo.Title = _comment;
                        _photo.ImageUrl = data.ImageUrl;
                        savePhoto(_photo);
                    } else {
                        showError("照片描述超过50个字");
                    }

                });

                $("#btnDelPhoto").click(function () {
                    deletePhoto(data.ID);
                });

                $("#btnBack").click(function () {
                    initMyPhotosPage();
                });
            });

        }

        function initPage() {
            //第一步检查cookie是否存在，如果存在就不用去访问微信服务器获取openid，直接使用cookies中的openid查询数据
            //库中的用户信息并写入cookie,如果不存在则访问微信服务器获取openid
            //第二步使用openid检查数据库中是否有该用户信息，如果数据库中没有，说明该用户是第一次登录，需要将用户信息
            //保存到数据库，然后取出用户信息并保存到cookie中；如果数据库中有，则取出用户信息保存到cookie中

            if (getCookie("jxbisai_user") !== "") {
                user = JSON.parse(getCookie("jxbisai_user"));
                openId = user.WechatOpenId;
                console.log("user:" + JSON.stringify(user));

            } else {
                user.WechatOpenId = "oAMP5shI6hdqW7Fs7quu9yuU3HKg";
                setCookie(JSON.stringify(user));
                //var code = GetQueryString("code");
                //var getTokenUrl = "../api/accesstoken/?code=" + code;

                //axios.get(getTokenUrl).then(function (response) {
                //    console.log(response)
                //    openId = response.data;
                //    user.WechatOpenId = openId;
                //    setCookie(JSON.stringify(user));
                //}).catch(function (error) {
                //    //window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb1f3698b4c90dccd&redirect_uri=http://www.shtraining.net/wxdemo/photos/index.html&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
                //});

            }

            setNavStatus("photoindex");
            setContentStatus("photoindex");
            bindMenuClick();
        }

        function getLastestPhotos() {
            getPhotos(" WHERE FileUrl='teacher' ORDER BY LikesCount DESC, Number DESC", "#list_lastest");
        }

        function getTopsPhotos() {
            getPhotos(" WHERE FileUrl='course' ORDER BY LikesCount DESC, Number DESC", "#list_tops");
        }

        function getPhotos(whereExpression, target) {

            //获取当前用户当天已点赞图片
            var date = new Date();
            var today = date.Format("yyyy-MM-dd");
            date.setDate(date.getDate() + 1);
            var tomorrow = date.Format("yyyy-MM-dd");
            var getLikedPhotosUrl = "../api/photolike?where= and wechatopenid='" + openId + "'" + "and createdat between '" + today + "' and '" + tomorrow + "'";

            $.getJSON(getLikedPhotosUrl, function (res) {
                setCookie("wusong_likedPhotos", JSON.stringify(res), 60);

                console.log(getCookie("wusong_likedPhotos"));

                //获取图片
                var data = {};
                data.photos = [];
                var pageSize = 10;
                var getPhotosUrl = "../api/photoitem?pagesize=" + pageSize + "&where=" + whereExpression;

                $.getJSON(getPhotosUrl, function (res) {
                    toastLoading.close();

                    data.photos = res.results;

                    //设置图片是否可点赞
                    var likedPhotos = JSON.parse(getCookie("wusong_likedPhotos"));
                    var likedLength = likedPhotos.count;
                    var likedPhotoIds = [];

                    for (var i = 0; i < likedLength; i++) {
                        likedPhotoIds.push(likedPhotos.results[i].ItemID);
                    }

                    console.log(likedPhotoIds);

                    var photosLength = res.count;

                    for (var j = 0; j < photosLength; j++) {
                        if (likedPhotoIds.indexOf(data.photos[j].ID) > -1) {
                            //此图片今天已被当前用户点赞
                            data.photos[j].IsLiked = 1;
                        } else {
                            data.photos[j].IsLiked = 0;
                        }
                    }


                    var html = template("list", data);
                    $(target).html(html);

                    bindLikeClick();
                    bindPhotoClick();

                    if (res.count === pageSize) {

                        $(".more").attr("data_lastestNumber", res.results[res.results.length - 1].Number);
                        $(".more").attr("data_lastestLikesCount", res.results[res.results.length - 1].LikesCount);

                        $(".more").click(function () {
                            var _lastestNumber = $(".more").attr("data_lastestNumber");
                            var _lastestLikesCount = $(".more").attr("data_lastestLikesCount");
                            //console.log(_lastestNumber);
                            //console.log(_lastestLikesCount);

                            var moreData = {};
                            moreData.photos = [];
                            var getMorePhotosUrl;
                            var limitedExpression;
                            if (target === "#list_lastest") {
                                limitedExpression = "and Number < " + _lastestNumber;
                            }
                            if (target === "#list_tops") {
                                limitedExpression = "and LikesCount <= " + _lastestLikesCount + " and ID not in (select ID from v_Photo_ItemDetails where LikesCount = " + _lastestLikesCount + " and Number >= " + _lastestNumber + ")";
                            }
                            getMorePhotosUrl = "../api/photoitem?pagesize=" + pageSize + "&where=" + limitedExpression + whereExpression;

                            $.getJSON(getMorePhotosUrl, function (res) {

                                moreData.photos = res.results;

                                //设置图片是否可点赞
                                likedPhotos = JSON.parse(getCookie("wusong_likedPhotos"));
                                likedLength = likedPhotos.count;
                                likedPhotoIds = [];

                                for (var i = 0; i < likedLength; i++) {
                                    likedPhotoIds.push(likedPhotos.results[i].ItemID);
                                }

                                photosLength = res.count;

                                for (var j = 0; j < photosLength; j++) {
                                    if (likedPhotoIds.indexOf(moreData.photos[j].ID) > -1) {
                                        //此图片今天已被当前用户点赞
                                        moreData.photos[j].IsLiked = 1;
                                    } else {
                                        moreData.photos[j].IsLiked = 0;
                                    }
                                }

                                if (res.count == pageSize) {

                                    $(target + " .waterfall").append(template("listMore", moreData));
                                    bindLikeClick();
                                    bindPhotoClick();
                                    $(".more").attr("data_lastestNumber", res.results[res.results.length - 1].Number);
                                    $(".more").attr("data_lastestLikesCount", res.results[res.results.length - 1].LikesCount);

                                } else if (res.count > 0) {

                                    $(target + " .waterfall").append(template("listMore", moreData));
                                    bindLikeClick();
                                    bindPhotoClick();
                                    $(".more").hide();
                                    $(".no_more").removeClass("hidden");
                                } else {
                                    $(".more").hide();
                                    $(".no_more").removeClass("hidden");
                                }

                            });

                        });
                    } else {
                        $(".more").hide();
                    }

                });
            });



        }

        function bindLikeClick() {

            $(".thumbup_btn").click(function () {

                var isLiked = $(this).attr("data_isLiked");

                if (isLiked == "0") {
                    var photoId = $(this).attr("data_photoId");
                    var model = {};
                    model.WechatOpenId = openId;
                    model.ItemID = photoId;
                    var span_thumbup_total = $(this).prev();
                    $(this).css("background-color", "#cccccc");
                    $(this).unbind();
                    addLike(model, span_thumbup_total);
                }

            });
        }

        function bindPhotoClick() {
            $(".item-cover").unbind();
            $(".item-cover").click(function () {
                var photoId = $(this).attr("data_Id");

                $.getJSON("../api/photoitem/" + photoId, function (res) {

                    var data = res.result;

                    //设置图片是否可点赞
                    var likedPhotos = JSON.parse(getCookie("wusong_likedPhotos"));
                    var likedLength = likedPhotos.count;
                    var likedPhotoIds = [];

                    for (var i = 0; i < likedLength; i++) {
                        likedPhotoIds.push(likedPhotos.results[i].ItemID);
                    }

                    if (likedPhotoIds.indexOf(photoId) > -1) {
                        //此图片今天已被当前用户点赞
                        data.IsLiked = 1;
                    } else {
                        data.IsLiked = 0;
                    }

                    $(".wrapper").append(template("tplModal", data));

                    $(".btn").click(function () {
                        var photoId = $(this).attr("data_photoId");
                        var isLiked = $(this).attr("data_isLiked");

                        if (isLiked == "0") {
                            var model = {};
                            model.WechatOpenId = openId;
                            model.ItemID = photoId;
                            var span_thumbup_total = $(".number span:eq(2)");
                            addLike(model, span_thumbup_total);

                            $(this).css("background-color", "#cccccc");
                            $(this).unbind();
                        }

                    });

                    $(".close").click(function () {
                        $(".modal").remove();
                        $("#modalContainer").remove();
                    });
                });

            })
        }

        function uploadUser() {

            //$("#message").html("ok-3");

            var model = { "OpenID": openId, "NickName": nickName, "HeadImgUrl": headImgUrl };

            $.ajax({
                url: "api/user/",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                data: JSON.stringify(model),
                error: function (data) {
                    console.log(data);
                },
                success: function (data) {
                    console.log("uploadUser is ok");
                },
                complete: function (data) {
                    $.getJSON("api/user/" + openId, function (data) {
                        setCookie("wusong_user", JSON.stringify(data), 60);
                        getArtilces();
                    });
                }
            });
        }

        function showLoading(title) {
            toastLoading = $(document).dialog({
                type: 'toast',
                infoIcon: '../asset/images/icon/loading.gif',
                infoText: title,
                autoClose: 5000
            });
        }

        function showError(title) {
            toastError = $(document).dialog({
                type: 'toast',
                infoIcon: '../asset/images/icon/fail.png',
                infoText: title,
                autoClose: 2500
            });
        }

        function showSuccess(title) {
            toastSuccess = $(document).dialog({
                type: 'toast',
                infoIcon: '../asset/images/icon/success.png',
                infoText: title,
                autoClose: 1000
            });
        }

        function login(userName, mobile) {
            var loginUrl = "../api/photouser?username=" + userName + "&mobile=" + mobile;

            $.ajax({
                url: loginUrl,
                dataType: "json",
                data: {},
                type: "GET",
                error: function (error) {
                    console.log(error);
                },
                beforeSend: function () {
                    showLoading("正在登录中");
                },
                success: function (res) {
                    toastLoading.close();

                    user = res.result;
                    if (user === null) {
                        showError('姓名或手机号错误');
                    } else {
                        setCookie("wusong_photo_user", JSON.stringify(user), 365);
                        initMyPhotosPage();
                    }

                },
                complete: function () {
                    toastLoading.close();
                }
            });
        }

        function reg(userName, mobile, school, role) {
            var regUrl = "../api/photouser";
            var model = {};
            model.username = userName;
            model.mobile = mobile;
            model.orginazation = school;
            model.wechatopenId = openId;
            model.roleId = role;

            $.getJSON("../api/photouser/checkmobile?mobile=" + mobile, function (res) {
                if (res.result === null) {
                    $.ajax({
                        url: regUrl,
                        dataType: "json",
                        data: JSON.stringify(model),
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        error: function (error) {
                            console.log(error);
                        },
                        beforeSend: function () {
                            showLoading("正在注册中");
                        },
                        success: function (res) {
                            user = res;
                            setCookie("wusong_photo_user", JSON.stringify(user), 365);
                            initMyPhotosPage();

                        },
                        complete: function () {
                            toastLoading.close();
                        }
                    });
                } else {
                    showError("手机号已被使用");
                }
            })
        }

        function addPhoto(imgUrl, comment) {
            var addPhotoUrl = "../api/photoitem";
            var _model = {};
            _model.title = comment;
            if (imgUrl == "") {
                showError("请先选择图片");
                return;
            }

            _model.imageurl = imgUrl;
            _model.userid = user.ID;

            $.ajax({
                url: addPhotoUrl,
                dataType: "json",
                data: JSON.stringify(_model),
                type: "POST",
                contentType: "application/json; charset=utf-8",
                error: function (error) {
                    console.log(error);
                },
                beforeSend: function () {
                    showLoading("数据上传中");
                },
                success: function (res) {
                    tmpUploadImageUrl = "";
                    showSuccess("提交成功");
                    toastLoading.close();
                    $("#a_my").click();
                },
                complete: function () {
                    toastLoading.close();
                }
            });
        }

        function savePhoto(model) {
            var savePhotoUrl = "../api/photoitem";

            $.ajax({
                url: savePhotoUrl,
                dataType: "json",
                data: JSON.stringify(model),
                type: "PUT",
                contentType: "application/json; charset=utf-8",
                error: function (error) {
                    console.log(error);
                },
                beforeSend: function () {
                    showLoading("数据上传中");
                },
                success: function (res) {
                    showSuccess("保存成功");
                    toastLoading.close();
                    $("#a_my").click();
                },
                complete: function () {
                    toastLoading.close();
                }
            });
        }

        function deletePhoto(id) {
            var deletePhotoUrl = "../api/photoitem/" + id;

            $.ajax({
                url: deletePhotoUrl,
                dataType: "json",
                data: {},
                type: "DELETE",
                contentType: "application/json; charset=utf-8",
                error: function (error) {
                    console.log(error);
                },
                beforeSend: function () {
                    showLoading("照片删除中");
                },
                success: function (res) {
                    showSuccess("删除成功");
                    toastLoading.close();
                    $("#a_my").click();
                },
                complete: function () {
                    toastLoading.close();
                }
            });
        }

        function saveUser(model) {

            if (model.Mobile !== user.Mobile) {
                $.getJSON("../api/photouser/checkmobile?mobile=" + model.Mobile, function (res) {
                    if (res.result === null) {
                        updateUser(model);
                    } else {
                        showError("手机号已被使用");
                    }
                })
            } else {
                updateUser(model);
            }

        }

        function updateUser(model) {
            var saveUserUrl = "../api/photouser";

            $.ajax({
                url: saveUserUrl,
                dataType: "json",
                data: JSON.stringify(model),
                type: "PUT",
                contentType: "application/json; charset=utf-8",
                error: function (error) {
                    console.log(error);
                },
                beforeSend: function () {
                    showLoading("数据上传中");
                },
                success: function (res) {
                    user = res;
                    setCookie("wusong_photo_user", JSON.stringify(user), 365);
                    showSuccess("保存成功");
                    toastLoading.close();
                    $("#a_my").click();
                },
                complete: function () {
                    toastLoading.close();
                }
            });
        }

        function addLike(model, total) {
            var addLikeUrl = "../api/photolike";

            $.ajax({
                url: addLikeUrl,
                contentType: "application/json; charset=utf-8",
                type: "POST",
                data: JSON.stringify(model),
                error: function (data) {
                    console.log(data);
                },
                success: function (data) {
                    $.getJSON("../api/photoitem/" + model.ItemID, function (res) {
                        total.html(res.result.LikesCount + " 票&nbsp;&nbsp;").addClass("total_pulse");
                        total.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
                            total.removeClass("total_pulse");
                        });

                        console.log(total.attr("data_type"));

                        if (total.attr("data_type") == "modal") {
                            $(".thumbup_total[data_photoId='" + model.ItemID + "']").html(res.result.LikesCount + " 票&nbsp;&nbsp;");
                            $(".thumbup_btn[data_photoId='" + model.ItemID + "']").css("background-color", "#cccccc").unbind();
                        }
                    });

                    var likedPhotos = {};
                    likedPhotos = JSON.parse(getCookie("wusong_likedPhotos"));
                    if (likedPhotos.count == 0) {
                        likedPhotos.results = [];
                    }
                    likedPhotos.results.push(model);
                    likedPhotos.count = likedPhotos.count + 1;
                    setCookie("wusong_likedPhotos", JSON.stringify(likedPhotos), 60);
                }
            });
        }
    </script>
</body>
</html>